﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.BaseConfigs;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.ForeEndModels.ErrorExplanations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace HamcoWcs.Main.Controllers.Common
{
    /// <summary>
    /// 报警信息控制器
    /// </summary>
    [ApiController]
    [ApiExplorerSettings(IgnoreApi = true)]
    [Route("[controller]")]
    public class AlarmController : BasicController
    {
        /// <summary>
        /// 
        /// </summary>
        public override string ControllerName => "AlarmController";

        /// <summary>
        /// 构造函数
        /// </summary>
        public AlarmController(WcsDbContext wcsDbContext, IMapper mapper, ILoggerService loggerService)
            : base(loggerService, mapper, wcsDbContext)
        {
        }

        /// <summary>创建故障信息</summary>
        [HttpPost(nameof(Create))]
        public IActionResult Create(UIAlarmExplanation alarmDto, [FromHeader] string userName = "")
        {
            alarmDto.Id = 0;
            if (string.IsNullOrEmpty(alarmDto.AlarmName)) return Json(ForeEndResult.Fail("故障名不得为空"));
            if (string.IsNullOrEmpty(alarmDto.ErrorType)) return Json(ForeEndResult.Fail("故障类型不得为空"));

            try
            {
                var alarm = _mapper.Map<AlarmExplanation>(alarmDto);
                _wcsDbContext.Add(alarm);
                _wcsDbContext.SaveChanges();

                var msg = $"{userName},创建故障信息->AlarmName:{alarmDto.AlarmName}";
                AddOperationLog(userName, msg);
                return Json(ForeEndResult.Ok);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return CreateFailureResult();
            }
        }


        /// <summary>删除故障信息</summary>
        [HttpPost("Delete")]
        public IActionResult Delete(AlarmExplanationDeleteDto deleteDto, [FromHeader] string userName = "")
        {
            try
            {
                var alarm = _wcsDbContext.AlarmExplanations.FirstOrDefault(x => x.Id == deleteDto.Id);

                if (alarm == null) return Json(ForeEndResult.Fail($"未找到Id为{deleteDto.Id}的报警信息"));

                _wcsDbContext.AlarmExplanations.Remove(alarm);
                _wcsDbContext.SaveChanges();

                var msg = $"{userName},删除故障信息->AlarmName:{alarm.AlarmName}";
                AddOperationLog(userName, msg);
                return Json(ForeEndResult.Ok);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return DeleteFailureResult();
            }
        }


        /// <summary>修改故障信息</summary>
        [HttpPost("Update")]
        public IActionResult Update(AlarmExplanationUpdateDto updateDto, [FromHeader] string userName = "")
        {
            try
            {
                var alarm = _wcsDbContext.AlarmExplanations.FirstOrDefault(x => x.Id == updateDto.Id);

                if (alarm == null) return Json(ForeEndResult.Fail($"未找到Id为{updateDto.Id}的报警信息"));

                var diffObjs = new List<DiffObj> { };

               


                if (updateDto.ErrorType != alarm.ErrorType)
                {
                    diffObjs.Add(new DiffObj(alarm.ErrorType, updateDto.ErrorType));
                    alarm.ErrorType = updateDto.ErrorType;
                }

                if (updateDto.Level != alarm.Level)
                {
                    diffObjs.Add(new DiffObj(alarm.Level, updateDto.Level));
                    alarm.Level = updateDto.Level;
                }

                if (updateDto.AlarmName != alarm.AlarmName)
                {
                    diffObjs.Add(new DiffObj(alarm.AlarmName, updateDto.AlarmName));
                    alarm.AlarmName = updateDto.AlarmName;
                }

                if (updateDto.Suggestion != alarm.Suggestion)
                {
                    diffObjs.Add(new DiffObj(alarm.Suggestion, updateDto.Suggestion));
                    alarm.Suggestion = updateDto.Suggestion;
                }

                if (updateDto.Summary != alarm.Summary)
                {
                    diffObjs.Add(new DiffObj(alarm.Summary, updateDto.Summary));
                    alarm.Summary = updateDto.Summary;
                }

                _wcsDbContext.AlarmExplanations.Update(alarm);
                _wcsDbContext.SaveChanges();


                var msg = $"{userName},修改故障信息:{string.Join(',', diffObjs.Select(d => d.ToString()))}";
                AddOperationLog(userName, msg);

                return Json(ForeEndResult.Ok);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return UpdateFailureResult();
            }
        }


        /// <summary>查询故障信息</summary>
        [HttpPost("Query")]
        public IActionResult Query(AlarmExplanationQueryDto query)
        {

            try
            {
                var queryable = _wcsDbContext.AlarmExplanations
                                            .AsQueryable()
                                            .VagueWhereOut(query, out int count, out int pageCount)
                                            .ToList();

                var data = _mapper.Map<List<UIAlarmExplanation>>(queryable);
                return Json(new ForeEndResult(data,count,pageCount));
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>查询指定故障信息</summary>
        [HttpPost("Lookup")]
        public IActionResult Lookup(AlarmExplanationLookupDto query)
        {

            try
            {
                var alarm =  _wcsDbContext.AlarmExplanations
                                        .AsQueryable()
                                        .FirstOrDefault(x => x.Module == query.Module
                                        && x.Code == query.Code);

                if (alarm == null)
                    alarm = new AlarmExplanation()
                    {
                        Code = query.Code,
                        Module = query.Module,
                        AlarmName = "Unknown Alarm",
                        Suggestion = "",
                        ErrorType = "",
                        Level = 0,
                        Summary = ""
                    };


                var data = _mapper.Map<UIAlarmExplanation>(alarm);
                var result = new ForeEndResult(data);
                return Json(result);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }

        /// <summary>
        /// 判断用
        /// </summary>
        public class DiffObj
        {
            /// <summary>
            /// 
            /// </summary>
            /// <param name="oldValue"></param>
            /// <param name="newValue"></param>
            public DiffObj(int oldValue, int newValue) : this(oldValue.ToString(), newValue.ToString())
            {
            }

            /// <summary>
            /// 
            /// </summary>
            /// <param name="oldValue"></param>
            /// <param name="newValue"></param>
            public DiffObj(string oldValue, string newValue)
            {
                OldValue = oldValue;
                NewValue = newValue;
            }

            /// <summary>
            /// 
            /// </summary>
            public string OldValue { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string NewValue { get; set; }

            /// <summary>
            /// 
            /// </summary>
            /// <returns></returns>
            public override string ToString()
            {
                return $"{OldValue}->{NewValue}";
            }
        }
    }
}
